<template>
  <div class="analysis-consultation">
    <div class="container py-4">
      <h1 class="text-center mb-4">八字算命</h1>
      
      <!-- 添加积分显示 -->
      <div class="points-info mb-3">
        <div class="row g-2 justify-content-center">
          <div class="col-auto">
            <div class="points-badge total-points">
              <i class="bi bi-coin me-2"></i>积分余额: {{ userPoints }}
            </div>
          </div>
          <div class="col-auto" v-if="lastConsumedPoints > 0">
            <div class="points-badge consumed-points">
              <i class="bi bi-dash-circle me-2"></i>本次消耗: {{ lastConsumedPoints }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="row">
        <div class="col-lg-8 mx-auto">
          <div class="card shadow">
            <div class="card-body">
              <div class="chat-container">
                <div class="chat-messages" ref="chatMessages">
                  <!-- 消息列表 -->
                  <template v-for="(message, index) in messages" :key="index">
                    <!-- 用户消息 -->
                    <div v-if="message.type === 'user'" class="message user-message">
                      <div class="message-content">
                        {{ message.text }}
                      </div>
                      <div class="message-footer">
                        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                        <div class="message-actions">
                          <copy-button :content="message.text" title="复制问题"></copy-button>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 系统消息 -->
                    <div v-else class="message system-message" :class="{ 
                      'typing-message': message.isTyping,
                      'special-message': message.isSpecial,
                      'info-message': message.isInfo
                    }">
                      <!-- 如果是正在加载状态且没有文本 -->
                      <div v-if="message.isTyping && !message.text" class="loading-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <!-- 显示消息文本 -->
                      <div v-else class="message-content">
                        <span v-html="message.text"></span>
                        <span v-if="message.isTyping" class="typing-cursor"></span>
                        <!-- 特殊消息的充值按钮 -->
                        <button v-if="message.hasRechargeButton" 
                          @click="goToRecharge" 
                          class="btn btn-recharge btn-lg mt-3">
                          <i class="bi bi-credit-card me-2"></i>
                          立即充值获取积分
                        </button>
                      </div>
                      <div class="message-footer">
                        <!-- 复制按钮和时间戳在同一行显示 -->
                        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                        <div class="message-actions" v-if="!message.isTyping">
                          <copy-button :content="message.text" title="复制回答"></copy-button>
                        </div>
                      </div>
                    </div>
                  </template>
                  
                  <!-- 等待API响应的加载指示器 -->
                  <div v-if="isWaitingForResponse" class="message system-message loading-message">
                    <div class="message-content">
                      <div class="thinking-animation">
                        <span>天机推衍</span>
                        <span class="thinking-dots">
                          <span>.</span>
                          <span>.</span>
                          <span>.</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="chat-input-wrapper">
                  <div class="input-group custom-input-group">
                    <div class="input-icon">
                      <i class="bi bi-stars"></i>
                    </div>
                    <input 
                      type="text" 
                      class="form-control custom-input" 
                      placeholder="请输入您的算命问题..." 
                      v-model="userInput"
                      @keyup.enter="validateAndSend"
                      :class="{'is-invalid': showInputError}"
                      :disabled="isLoading"
                    >
                    <button 
                      class="btn btn-send" 
                      @click="validateAndSend"
                      :disabled="isLoading"
                    >
                      <i class="bi" :class="[isLoading ? 'bi-hourglass-split' : 'bi-send-fill']"></i>
                      <span>{{ isLoading ? '天机推衍...' : '获取命理' }}</span>
                    </button>
                  </div>
                  <div class="invalid-feedback" v-if="showInputError">
                    请输入您想咨询的问题
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="card mt-4 question-card">
            <div class="card-header bg-light">
              <h5 class="mb-0">
                <i class="bi bi-stars me-2"></i>
                算命常见问题
              </h5>
            </div>
            <div class="card-body">
              <div class="quick-questions">
                <button 
                  v-for="(question, index) in suggestedQuestions" 
                  :key="index"
                  class="btn btn-question me-2 mb-2"
                  @click="askSuggestedQuestion(question)"
                  :disabled="isLoading"
                >
                  <i class="bi bi-chat-text me-2"></i>
                  {{ question }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../store/userStore'
import { mapState } from 'pinia'
import { askService } from '../api'
import { userService } from '../api'
import CopyButton from '../components/CopyButton.vue'

export default {
  name: 'Analysis',
  components: {
    CopyButton
  },
  data() {
    return {
      userInput: '',
      showInputError: false,
      isLoading: false,
      isWaitingForResponse: false, // 是否正在等待API首次响应
      // 积分系统相关
      pointsPerQuestion: 10, // 每次提问消耗的积分
      lastConsumedPoints: 0, // 上次消耗的积分
      messages: [
        {
          type: 'system',
          text: '您好，欢迎来到八字算命。我可以基于您的生辰八字，为您提供全面命理分析。请告诉我您的出生年月日时，或直接提问您关心的问题。',
          timestamp: new Date()
        }
      ],
      suggestedQuestions: [
        '我的命运如何？',
        '我的五行缺什么？',
        '我今年的运势怎么样？',
        '我的性格特点是什么？'
      ],
      typingSpeed: 10, // 打字机效果的速度（毫秒/字符）
      // 预设的回答库
      responseMap: {
        '我的命运如何？': '根据您的八字，您命中五行平衡，但火土较旺。一生事业有成，中年后运势渐佳。您善于沟通，人缘较好，适合从事需要与人打交道的工作。',
        '我的五行缺什么？': '分析您的八字，您五行中水较弱，建议在日常生活中可以多佩戴黑色或蓝色饰品，多亲近水源，有助于平衡五行。',
        '我今年的运势怎么样？': '今年是您的转运年，上半年可能面临一些挑战，但下半年运势明显好转。事业上有新的机遇，感情上会有意外惊喜。',
        '我的性格特点是什么？': '您八字中木火较旺，性格开朗活泼，富有创造力和领导才能。做事有自己的主见，但有时过于理想化，可以适当提高务实精神。'
      }
    }
  },
  computed: {
    ...mapState(useUserStore, ['userPoints'])
  },
  methods: {
    validateAndSend() {
      // 检查用户输入是否为空
      if (!this.userInput.trim()) {
        this.showInputError = true;
        setTimeout(() => {
          this.showInputError = false;
        }, 3000);
        return;
      }
      
      this.showInputError = false;
      this.sendMessage();
    },
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) {
        this.showInputError = true;
        setTimeout(() => { this.showInputError = false; }, 2000);
        return;
      }

      // 清除上一次的积分消耗显示
      this.lastConsumedPoints = 0;

      const userMessage = {
        type: 'user',
        text: this.userInput,
        timestamp: new Date()
      };
      this.messages.push(userMessage);
      
      // 清空输入框并滚动到底部
      const userQuestion = this.userInput;
      this.userInput = '';
      this.scrollToBottom();
      
      this.isLoading = true;
      this.isWaitingForResponse = true; // 开始等待API响应
      
      try {
        // 使用流式响应替代原来的一次性请求
        await askService.askQuestionStream(
          userQuestion,
          // 处理接收到的每个块
          (chunk) => {
            this.isWaitingForResponse = false; // 收到第一个响应后不再显示加载动画
            
            // 查找最后一条系统消息或创建一个新的
            let responseMessage;
            if (this.messages.length > 0 && this.messages[this.messages.length - 1].type === 'system' && 
                this.messages[this.messages.length - 1].isTyping) {
              // 使用现有的正在输入的消息
              responseMessage = this.messages[this.messages.length - 1];
              responseMessage.fullText = (responseMessage.fullText || '') + chunk;
              this.animateTyping(responseMessage);
            } else {
              // 创建新的系统消息
              responseMessage = {
                type: 'system',
                text: '',
                fullText: chunk,
                displayedChars: 0,
                timestamp: new Date(),
                isTyping: true
              };
              this.messages.push(responseMessage);
              this.animateTyping(responseMessage);
            }
            
            this.scrollToBottom();
          },
          // 处理完成回调
          this.handleChatComplete,
          // 处理错误回调
          (error) => {
            console.error('发送消息失败', error);
            this.lastConsumedPoints = 0; // 确保在错误时清除积分消耗显示
            this.isWaitingForResponse = false;
            
            const errorMsg = error?.response?.data?.message || error?.message || '发送失败，请稍后重试';
            const errorDetail = error?.response?.data?.detail || '';
            const errorStatus = error?.response?.status;
            
            // 检查是否积分不足错误 - 检查消息文本或者特定的400错误码和detail字段
            if (errorMsg.includes('积分不足') || 
                (errorStatus === 400 && errorDetail.includes('积分不足'))) {
              // 创建一个特殊的系统消息，包含充值按钮的提示
              this.messages.push({
                type: 'system',
                text: '您的积分不足，无法继续使用分析服务。请先充值后再继续。',
                timestamp: new Date(),
                isSpecial: true, // 标记为特殊消息
                hasRechargeButton: true // 添加充值按钮标记
              });
              
              // 静默更新用户积分，但不显示具体数值
              setTimeout(async () => {
                // 使用优化的方法获取用户积分
                const userStore = useUserStore();
                await userStore.getUserScoreAfterChat();
              }, 500);
            } else {
              // 获取最后一条消息（如果有）
              if (this.messages.length > 0 && 
                  this.messages[this.messages.length - 1].type === 'system' && 
                  this.messages[this.messages.length - 1].isTyping) {
                // 如果最后一条是正在输入的系统消息，更新它
                const lastMessage = this.messages[this.messages.length - 1];
                lastMessage.text = errorMsg || errorDetail || '发送失败，请稍后重试';
                lastMessage.isTyping = false;
              } else {
                // 否则添加新的错误消息
                this.messages.push({
                  type: 'system',
                  text: errorMsg || errorDetail || '发送失败，请稍后重试',
                  timestamp: new Date(),
                  isTyping: false
                });
              }
            }
            
            this.isLoading = false;
            this.scrollToBottom();
          }
        );
      } catch (error) {
        this.handleApiError(error);
      }
    },
    // 处理完成回调
    handleChatComplete() {
      this.isLoading = false;
      this.isWaitingForResponse = false;
      
      // 找到最后一个正在输入的消息并完成它
      if (this.messages.length > 0) {
        const lastMessage = this.messages[this.messages.length - 1];
        if (lastMessage.type === 'system' && lastMessage.isTyping) {
          lastMessage.text = lastMessage.fullText;
          lastMessage.isTyping = false;
        }
      }
      
      // 延迟500毫秒后重新获取用户积分，确保服务器有时间完成积分更新
      setTimeout(async () => {
        // 使用优化的方法获取用户积分，包含重试逻辑
        const userStore = useUserStore();
        const result = await userStore.getUserScoreAfterChat();
        
        // 如果积分更新成功，显示消耗的积分在顶部，而不是作为消息
        if (result && result.success && result.pointsDiff > 0) {
          this.lastConsumedPoints = result.pointsDiff;
        }
        
        console.log('聊天完成，更新用户积分');
      }, 500);
      
      this.scrollToBottom();
    },
    // 实现打字机效果的动画
    animateTyping(message) {
      // 如果已有定时器，先清除
      if (message.typingTimer) {
        clearTimeout(message.typingTimer);
      }
      
      const typeNextChar = () => {
        // 如果当前显示字符数小于完整文本长度，继续添加字符
        if (message.displayedChars < message.fullText.length) {
          // 更新当前显示的字符数
          message.displayedChars += 1;
          // 更新消息文本
          message.text = message.fullText.substring(0, message.displayedChars);
          // 继续动画
          message.typingTimer = setTimeout(typeNextChar, this.typingSpeed);
        } else {
          // 动画完成
          message.text = message.fullText;
        }
        this.scrollToBottom();
      };
      
      // 开始动画
      message.typingTimer = setTimeout(typeNextChar, this.typingSpeed);
    },
    handleApiError(error) {
      console.error('发送消息失败', error);
      this.lastConsumedPoints = 0; // 确保在错误时清除积分消耗显示
      const errorMsg = error?.response?.data?.message || error?.message || '发送失败，请稍后重试';
      const errorDetail = error?.response?.data?.detail || '';
      const errorStatus = error?.response?.status;
      
      // 检查是否积分不足错误 - 检查消息文本或者特定的400错误码和detail字段
      if (errorMsg.includes('积分不足') || 
          (errorStatus === 400 && errorDetail.includes('积分不足'))) {
        // 创建一个特殊的系统消息，包含充值按钮的提示
        this.messages.push({
          type: 'system',
          text: '您的积分不足，无法继续使用分析服务。请先充值后再继续。',
          timestamp: new Date(),
          isSpecial: true, // 标记为特殊消息
          hasRechargeButton: true // 添加充值按钮标记
        });
        
        // 静默更新用户积分，但不显示具体数值
        setTimeout(async () => {
          // 使用优化的方法获取用户积分
          const userStore = useUserStore();
          await userStore.getUserScoreAfterChat();
        }, 500);
      } else {
        // 处理其他普通错误
        if (this.messages.length > 0 && this.messages[this.messages.length - 1].isTyping) {
          const placeholderMessage = this.messages[this.messages.length - 1];
          placeholderMessage.text = errorMsg || errorDetail || '发送失败，请稍后重试';
          placeholderMessage.isTyping = false;
        } else {
          this.messages.push({
            type: 'system',
            text: errorMsg || errorDetail || '发送失败，请稍后重试',
            timestamp: new Date()
          });
        }
      }
      
      this.isLoading = false;
      this.isWaitingForResponse = false;
      this.scrollToBottom();
    },
    askSuggestedQuestion(question) {
      if (this.isLoading) return;
      this.userInput = question;
      this.validateAndSend();
    },
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    scrollToBottom() {
      // 使用nextTick确保DOM已更新
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages;
        if (chatMessages) {
          // 添加平滑滚动效果
          chatMessages.scrollTo({
            top: chatMessages.scrollHeight,
            behavior: 'smooth'
          });
        }
      });
    },
    insertQuestion(question) {
      this.userInput = question;
    },
    goToRecharge() {
      // 跳转到充值页面
      this.$router.push('/recharge');
    }
  },
  watch: {
    // 监听消息数组的变化
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  },
  mounted() {
    this.scrollToBottom();
    // 从Pinia store初始化用户积分
    const userStore = useUserStore()
  }
}
</script>

<style scoped>
/* 八字算命页面整体样式 */
.analysis-consultation {
  /* background-color: #faf5ff; */
  min-height: 100vh;
}

/* 积分显示 */
.points-info {
  display: flex;
  justify-content: center;
}

.points-badge {
  padding: 5px 12px;
  border-radius: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.total-points {
  background-color: #e9f5ff;
  color: #0d6efd;
}

.consumed-points {
  background-color: #fff2e9;
  color: #fd7e14;
}

/* 聊天界面样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 65vh;
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 60px;
}

.message {
  padding: 12px 15px;
  border-radius: 15px;
  max-width: 85%;
  position: relative;
  animation: fadeIn 0.3s ease-out;
}

.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #4a6cf7 0%, #2954e0 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.system-message {
  align-self: flex-start;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  color: #333;
  border-bottom-left-radius: 4px;
  transition: all 0.3s ease;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.message-content {
  line-height: 1.5;
  word-break: break-word;
}

/* 消息底部信息栏 */
.message-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 4px;
  gap: 8px;
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.7);
}

.system-message .message-footer {
  color: #888;
}

.user-message .message-footer {
  color: rgba(255, 255, 255, 0.7);
}

.message-time {
  font-size: 0.75rem;
}

.message-actions {
  display: flex;
  align-items: center;
}

/* 输入框区域 */
.chat-input-wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background-color: white;
  border-top: 1px solid #eee;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.custom-input-group {
  position: relative;
  border-radius: 25px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.input-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7c3aed;
  z-index: 10;
}

.custom-input {
  border: none;
  padding-left: 45px;
  height: 50px;
  background-color: #f8f9fa;
}

.custom-input:focus {
  box-shadow: none;
  background-color: white;
}

.btn-send {
  background: linear-gradient(135deg, #9f7aea 0%, #7c3aed 100%);
  color: white;
  border: none;
  padding: 0.5rem 1.5rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-send:hover {
  background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
  color: white;
}

.btn-send i {
  font-size: 1.1rem;
}

/* 问题卡片样式 */
.question-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.btn-question {
  background-color: #f3ebff;
  color: #7c3aed;
  border: none;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.btn-question:hover {
  background-color: #e9d8fd;
  transform: translateY(-2px);
}

.btn-recharge {
  background: linear-gradient(135deg, #f6ad55 0%, #ed8936 100%);
  border: none;
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-recharge:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(237, 137, 54, 0.4);
}

/* 加载动画 */
.loading-message {
  background-color: transparent !important;
  box-shadow: none !important;
}

.thinking-animation {
  display: flex;
  align-items: center;
  color: #6c757d;
  font-style: italic;
}

.thinking-dots span {
  animation: loadingDots 1.4s infinite ease-in-out both;
  margin-left: 2px;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 16px;
  background-color: #333;
  margin-left: 2px;
  vertical-align: middle;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

.typing-message .message-content {
  position: relative;
}

/* 消息操作菜单样式 */
.message-actions {
  display: none;
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
}

.message:hover .message-actions {
  display: block;
}

.message-content {
  position: relative;
  width: 100%;
}

.user-message .message-actions {
  color: white;
}

.system-message .message-actions {
  color: #333;
}

/* 特殊消息样式 */
.special-message {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  border-left: 4px solid #ffc107;
}

.info-message {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-left: 4px solid #2196f3;
}

/* 加载中的动画点 */
.loading-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin: 0 3px;
  border-radius: 50%;
  background-color: #6c757d;
  opacity: 0.6;
  animation: loadingDots 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loadingDots {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 积分警告样式 */
.points-warning {
  background-color: #fff3cd;
  border-left: 4px solid #ffc107;
  padding: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* 淡入动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>